import * as services from 'services/profile';
import { routerRedux } from 'dva/router';
import { Toast } from 'antd-mobile';

export default {

  namespace: 'profile',

  state: {
    profile: {},
    portrait: {},
    gender: 0,
    modules: "",
    disabled: false,
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

  effects: {
    * getProfile({ payload }, { call, put }) {
      const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
      if(auth){
         let hospitalId = auth.hospitalId;
         let patientId = auth.patientId;
         const profile = yield call(services.queryProfile, hospitalId, patientId);
        yield put({ type: 'save', payload: { profile:profile.data, gender: profile.data.gender} });
      }
     
    },

    * getHeadPortrait({ payload: { patientId, hospitalId, mediaId }}, { call, put}) {
      try {
        let hospitalId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).hospitalId;
        let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
        yield call(services.queryHeadPortrait, patientId, hospitalId, mediaId);
        Toast.success('上传成功',1.5);
        yield put(
            routerRedux.replace({
               pathname: `/settings`,
          })
        );
      } catch(e){
        Toast.fail('上传失败',1.5);
      }
    },

    * updateProfile({ payload: data }, { call, put }) {
      yield call(services.updateProfile, data);
      Toast.success('更新成功');
      yield put(routerRedux.goBack());
    },

    * updatePassword({ payload: data }, { call, put }) {
      yield call(services.updatePassword, data);
      Toast.success('恭喜您，密码修改成功',1);
      yield put(routerRedux.goBack());
    },

    * updateMobile({ payload: data }, { call, put }) {
      yield call(services.updateMobile, data);
      Toast.success('更新成功');
      yield put(routerRedux.go(-2));
    },

    * getGetModules({ payload: { hospitalId } }, { call, put }){// 动态获取测评模块
       const modules = yield call(services.queryGetModules, hospitalId);
       yield put ({type: "save", payload: { modules: modules.data }});
    }
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (/(settings|profile|qrcode)$/.test(pathname)) {
          dispatch({ type: 'getProfile' });
        }
        if(/scale$/.test(pathname)){
             const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
             if(auth){
                dispatch({type:"getGetModules",payload:{hospitalId: auth.hospitalId || 1}});
                // 通过不同的hid的值进行动态的显示测评模块
             }
        }
      });
    },
  },
}
